<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="模板主题" prop="templateTheme">
        <el-input
          v-model="queryParams.templateTheme"
          placeholder="请输入模板主题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="templateType">
          <el-select
            v-model="queryParams.templateType"
            placeholder="请选择模板类型"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="dict in taskTemplateType"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"

        >导入</el-button>
       <!-- v-hasPermi="['task:template:import']"-->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="importTemplate"
        >导入模板下载</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主题" align="center" prop="templateTheme" />
      <el-table-column label="类型" align="center" prop="templateType" :formatter="typeFormat"/>
      <el-table-column label="添加时间" align="center" prop="createTime"/>
      <el-table-column label="创建人" align="center" prop="createUserName" />
      <el-table-column label="是否启用" align="center" prop="isUse" :formatter="statusFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEnable(scope.row)"

          >{{scope.row.isUse == 0?'禁用':"启用"}}</el-button>
         <!-- v-hasPermi="['task:template:enable']"-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"

          >查看</el-button>
         <!-- v-hasPermi="['task:content:view']"-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['task:task:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form :inline="true"  :model="upload" :rules="rules" label-width="68px">
        <el-form-item label="主题:" prop ="templateTheme">
          <el-input v-model="upload.templateTheme"  placeholder="请输入主题" size="small"/>
        </el-form-item>
        <el-form-item label="类型:" prop = "templateType">
          <el-select
            v-model="upload.templateType"
            placeholder="请选择模板类型"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="dict in taskTemplateType"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-upload
          :on-change="handleUploadFile"
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?templateTheme=' + upload.templateTheme+'&templateType='+upload.templateType"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="uploadCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="detailContent.title" :visible.sync="detailContent.open" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"

          >新增</el-button>
          <!--v-hasPermi="['task:content:add']"-->
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"

          >修改</el-button>
          <!--v-hasPermi="['task:content:edit']"-->
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"

          >删除</el-button>
         <!-- v-hasPermi="['task:content:remove']"-->
        </el-col>
      </el-row>

      <el-table v-loading="contentloading" :data="contentList" @selection-change="handleSelectionChange" >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" align="center" prop="serialNumber" />
        <el-table-column label="事项名称" width="200" align="center" prop="itemName" />
        <el-table-column label="法律依据" align="center" prop="legalBasis" />
        <el-table-column label="检查内容" align="center" prop="checkContent" />
      </el-table>

      <pagination
        v-show="contenttotal>0"
        :total="contenttotal"
        :page.sync="queryContentParams.pageNum"
        :limit.sync="queryContentParams.pageSize"
        @pagination="getdetailList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDetailForm">确 定</el-button>
        <el-button @click="detailcancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 添加或修改任务模板内容对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="序号" prop="serialNumber">
          <el-input v-model="form.serialNumber" placeholder="请输入序号" />
        </el-form-item>
        <el-form-item label="事项名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入事项名称" />
        </el-form-item>
        <el-form-item label="法律依据" prop="legalBasis">
          <el-input v-model="form.legalBasis" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="检查内容" prop="checkContent">
          <el-input v-model="form.checkContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, exportTask,importTemplate ,changeUseStatus} from "@/api/task/template";
import { listContent, getContent, delContent, addContent, updateContent, exportContent } from "@/api/task/content";
import { getToken } from "@/utils/auth";

export default {
  name: "Task",
  data() {
    return {
      // 遮罩层
      loading: true,
        contentloading: true,
      // 选中数组
      ids: [],
        itemNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
        contenttotal:0,

        // 启用状态字典
        taskTemplateUseStatus: [],
        // 任务类型字典
        taskTemplateType: [],
      // 检查模板表格数据
      taskList: [],
        contentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
        //是否上传文件
        handleUploadFileFlag:0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateTheme: undefined,
        templateType: undefined,
        isUse: undefined,
        deptId: undefined,
        createId: undefined,
        updateId: undefined,
      },
        queryContentParams: {
            pageNum: 1,
            pageSize: 10,
            templateId: undefined,
            serialNumber: undefined,
            itemName: undefined,
            legalBasis: undefined,
            checkContent: undefined,
            createId: undefined,
            updateId: undefined,
        },
        // 导入参数
        upload: {
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 模板主题
            templateTheme:undefined,
            templateType:undefined,
            //模板类型 1-双随机 2-周期
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/task/template/importData"
        },

        detailContent:{
          open: false,
            title:""

        },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        templateTheme: [
          { required: true, message: "模板主题不能为空", trigger: "blur" }
        ],
        templateType: [
          { required: true, message: "模板类型（1-双随机任务;2-周期任务;）不能为空", trigger: "blur" }
        ],
          serialNumber: [{required: true, message: "序号不能为空", trigger: "blur"}],
          itemName: [{required: true, message: "事项名称不能为空", trigger: "blur"}],
          legalBasis: [{required: true, message: "法律依据不能为空", trigger: "blur"}],
          checkContent: [{required: true, message: "内容及要求不能为空", trigger: "blur"}]
      }
    };
  },
  created() {
    this.getList();
      this.getDicts("task_template_type").then(response => {
          this.taskTemplateType = response.data;
      });
      this.getDicts("task_template_use_status").then(response => {
          this.taskTemplateUseStatus = response.data;
      });
  },
  methods: {
    /** 查询检查模板列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

      getdetailList(){
        this.contentloading = true;
          listContent(this.queryContentParams).then(response => {
              this.contentList = response.rows;
              this.contenttotal = response.total;
              this.contentloading = false;
          });
      },
      // 状态字典翻译
      statusFormat(row, column) {
          return this.selectDictLabel(this.taskTemplateUseStatus, row.isUse);
      },
      // 类型典翻译
      typeFormat(row, column) {
          return this.selectDictLabel(this.taskTemplateType, row.templateType);
      },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
      handleUploadFile(){
        this.handleUploadFileFlag = 1;
      },
      uploadCancel(){
          this.upload.open = false;
          this.$refs.upload.clearFiles();

      },
      detailcancel(){
        this.detailContent.open = false;
        this.detailreset();
        this.queryContentReset();
      },
      submitDetailForm(){
          this.detailContent.open = false;
      },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        templateTheme: undefined,
        templateType: undefined,
        isUse: undefined,
        deptId: undefined,
        delFlag: undefined,
        createTime: undefined,
        createId: undefined,
        updateTime: undefined,
        updateId: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
      resetUpload(){
        this.upload.templateTheme = undefined;
        this.upload.templateType = undefined;
        this.handleUploadFileFlag = 0;

      },

      detailreset() {
          this.form = {
              id: undefined,
              templateId: undefined,
              serialNumber: undefined,
              itemName: undefined,
              legalBasis: undefined,
              checkContent: undefined,
              delFlag: undefined,
              createTime: undefined,
              createId: undefined,
              updateTime: undefined,
              updateId: undefined,
              remark: undefined
          };
      },
      queryContentReset() {
        this.queryContentParams = {
            pageNum: 1,
            pageSize: 10,
            templateId: undefined,
            serialNumber: undefined,
            itemName: undefined,
            legalBasis: undefined,
            checkContent: undefined,
            createId: undefined,
            updateId: undefined,
        };
      },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
        this.itemNames = selection.map(item => item.itemName)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        getContent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 启用禁用按钮操作*/
    handleEnable(row){
        //只能一个个禁用，如要更改 添加       const ids = row.id || this.ids;
        const id = row.id;
        const templateTheme = row.templateTheme;
        const useStatus = row.isUse;
        this.$confirm('是否确认更改主题为"' + templateTheme + '"的启用状态?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        }).then(function() {
            return changeUseStatus(id,useStatus);
        }).then(() => {
            this.getList();
            this.msgSuccess("更改成功");
        }).catch(function() {});

    },
      /** 下载模板操作 */
      importTemplate() {
          importTemplate().then(response => {
              this.download(response.msg);
          });
      },
    handleImport() {
          this.resetUpload();
        this.upload.title = "检查内容模板导入";
        this.upload.open = true;
    },
      // 二级菜单弹出load数据
      handleDetail(row){
          this.contentloading = true;

          this.queryContentParams.templateId = row.id;
          listContent(this.queryContentParams).then(response => {
              this.contentList = response.rows;
              this.contenttotal = response.total;
              this.contentloading = false;
          });
          this.detailContent.title = "模板内容明细";
          this.detailContent.open = true;
      },
      // 提交上传文件
      submitFileForm() {
          if(!this.upload.templateType || !this.upload.templateTheme){
              this.msgError("请输入必填项");
              return;
          }
          if(this.handleUploadFileFlag != 1){
              this.msgError("上传文件不能为空");
              return;
          }
          this.$refs.upload.submit();
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
      },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
              this.form.templateId = this.queryContentParams.templateId;
              updateContent(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getdetailList();
              }
            });
          } else {
              this.form.templateId = this.queryContentParams.templateId;
              addContent(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getdetailList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const itemNames = row.itemName || this.itemNames;
      this.$confirm('是否确认删除任务模板事项名称为"' + itemNames + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delContent(ids);
        }).then(() => {
          this.getdetailList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有检查模板数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportTask(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
